<template>
  <div class="dashboard-container">
    <div class="dashboard-head">
      <div class="header_title">
        <h2>
          用电安全物联网平台
        </h2>
        <button class="dashboard-button" @click="loginOut" title="退出">
          <i class="fa fa-mail-reply" aria-hidden="true"></i>
        </button>
      </div>
    </div>
    <div class="control-wrapper">
      <clock />
      <h2 class="title">{{defaultTitle}}</h2>
      <p class="subtitle">用电高峰时段<span>{{cityInfo.peakHour}}</span></p>
    </div>
    <div class="count-wrapper">
      <div class="single-count">
        企业数<span>{{!!companyList?companyList.length:0}}</span>个
      </div>
      <div class="single-count">
        分路总数<span>{{cityInfo.deviceTotal}}</span>个
      </div>
      <div class="single-count">
        今日异常事件<span>{{cityInfo.errorNumber}}</span>起
      </div>
    </div>
    <div class="dashboard-left">
      <leftContent />
    </div>
    <div class="dashboard-right">
      <rightContent />
    </div>
    <div id="city-pro-map-bottle" class="dashboard-map" ref="dashboardMapRef1" />
  </div>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
import clock from "@/components/clock";
import leftContent from "./components/leftContent";
import rightContent from "./components/rightContent";
import { getVideoCity, getGeoJson } from "@/api";
import { echartOption, provinceList } from "./utils";
import { idMapProvince, idMapCity } from "@/utils/mapConfig";
import Print from "./Print";
import "./index.scss";
import AMap from "AMap";

// 判断当前name是省份还是城市，并且返回对应的code
function findCityName(rname, code) {
  if (rname === "ROLE_PROVINCE") {
    return idMapProvince.find(t => t.code === code).key;
  } else {
    let startKey = code.substring(0, 2);
    if (!startKey) {
      alert(startKey);
      return false;
    }
    let whichProvince = idMapProvince.find(t => t.code.startsWith(startKey))
      .code;
    return idMapCity[whichProvince].find(t => t.code == code).key;
  }
}

export default {
  name: "ProvinceAndCityMap",
  components: {
    clock,
    leftContent,
    rightContent
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  beforeDestroy() {
    // if (this.mapBottle) window.addEventListener("resize", () => false);
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.mapBottle = this.echarts.init(this.$refs.dashboardMapRef1);
    //   this.mapBottle.showLoading({
    //     text: "加载ing",
    //     color: "#154E90",
    //     textColor: "#fff",
    //     zlevel: 0
    //   });
    // });
    // this.getSingleCityInfor();
    this.initMap();
  },

  methods: {
    ...mapActions(["getSingleCity", "logout"]),

    getSingleCityInfor() {
      const vm = this;
      const { areaId, areaName, areaCode, rname } = vm.userInfo;
      this.defaultTitle = areaName;
      const key = findCityName(rname, areaCode);
      getGeoJson(key).then(res => {
        if (res.code === 200 && !!res.data) {
          vm.echarts.registerMap(areaName, res.data);
          this.getSingleCity(areaId).then(res => {
            vm.cityInfo = res;
            let companyList = res.companyList || [];
            this.companyList = JSON.parse(JSON.stringify(companyList));
            let option = JSON.parse(JSON.stringify(echartOption));
            let data = new Print(areaName, companyList, option).start();
            this.$nextTick(() => {
              vm.mapBottle.setOption(data);
              vm.mapBottle.hideLoading();
              window.addEventListener("resize", () => {
                vm.mapBottle.resize();
              });
            });
          });
        } else {
          vm.$Message.error("未知错误，请刷新重试");
        }
      });
    },

    initMap() {
      const vm = this;
      const { areaId, areaName, areaCode, rname } = vm.userInfo;
      this.defaultTitle = areaName;
      let level = rname === "ROLE_PROVINCE" ? "province" : "city";
      this.getSingleCity(areaId).then(res => {
        const companyList =res.companyList;
        AMap.plugin(["AMap.DistrictSearch"], function() {
          const district = new AMap.DistrictSearch({
            subdistrict: 0, //返回下一级行政区
            level,
            showbiz: false,
            extensions: "all" //返回行政区边界坐标组等具体信息
          }).search(areaName, function(status, result) {
            result = result.districtList[0];
            let bounds = result.boundaries;
            vm.mapBottle = new AMap.Map("city-pro-map-bottle", {
              mapStyle: "amap://styles/cf977c5011663f8d3af2a00349d86a51",
              center: result.center,
              pitch: 52,
              viewMode: "3D", //开启3D视图,默认为关闭
              labelzIndex: 130,
              cursor: "pointer",
              skyColor: "#fff",
              isHotspot: false
            });

            vm.mapBottle.on("complete", function() {
              vm.mapBottle.plugin(["AMap.DistrictLayer"], function() {
                let disCountry = new AMap.DistrictLayer.Country({
                  SOC: "CHN",
                  zIndex: 1,
                  depth: 1,
                  styles: {
                    "province-stroke": "cornflowerblue",
                    fill: "rgba(0,0,0,0)"
                  }
                });
                disCountry.setMap(vm.mapBottle);
              });
              var prism = new AMap.Object3D.Wall({
                path: bounds,
                height: 5000,
                color: "#0088ffcc"
              });
              prism.transparent = true;
              var object3Dlayer = new AMap.Object3DLayer({});
              object3Dlayer.add(prism);
              object3Dlayer.setMap(vm.mapBottle);

              var tianditu = new AMap.TileLayer({
                zIndex: -1,
                getTileUrl:
                  "http://t{1,2,3,4}.tianditu.gov.cn/DataServer?tk=2ce94f67e58faa24beb7cb8a09780552&T=ter_w&x=[x]&y=[y]&l=[z]"
              });
              tianditu.setMap(vm.mapBottle);
            });
          });
        });
      });
    },

    loginOut() {
      this.$Modal.confirm({
        title: "提示",
        content: "<p>即将退出</p><p>是否继续？</p>",
        onOk: () => {
          this.logout().then(() => {
            this.$Message.info("退出登录");
            setTimeout(() => {
              location.reload();
            }, 300);
          });
        },

        onCancel: () => {
          return false;
        }
      });
    }
  },

  data() {
    return {
      defaultTitle: "",
      mapBottle: null,
      cityInfo: {},
      companyList: []
    };
  }
};
</script>
